package com.nuaa.yupicturebackend.service.impl;

import com.google.gson.Gson;
import com.nuaa.yupicturebackend.model.entity.Staff;
import com.nuaa.yupicturebackend.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ortonzhu
 * @Date 2025/2/23 13:12
 */
@Service
@Slf4j
public class StaffServiceImpl implements StaffService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private Gson gson;

    // 缓存符合条件的员工到Redis Hash中
    public void cacheEligibleStaff(List<Staff> staffList, String hashKey) {
        Map<String, String> serializedStaffMap = staffList.stream()
                .collect(Collectors.toMap(staff -> staff.getStaffId().toString(), this::serializeStaff));
        stringRedisTemplate.opsForHash().putAll(hashKey, serializedStaffMap);
    }

    // 序列化 Staff 对象为 JSON 字符串
    private String serializeStaff(Staff staff) {
        return gson.toJson(staff);
    }

    // 反序列化 JSON 字符串为 Staff 对象
    private Staff deserializeStaff(String serializedStaff) {
        return gson.fromJson(serializedStaff, Staff.class);
    }

    // 根据员工ID查找并返回该员工对象
    public Staff findEligibleStaff(Integer staffId, String hashKey) {
        String serializedStaff = (String) stringRedisTemplate.opsForHash().get(hashKey, staffId.toString());
        if (serializedStaff != null) {
            return deserializeStaff(serializedStaff);
        }
        return null; // 如果未找到匹配的员工
    }

    @PostConstruct
    public void init() {
        String hashKey = "Bole:eligibleStaff";
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(hashKey))) {
            log.info("初始化员工缓存完成");
            List<Staff> eligibleStaff = Arrays.asList(
                    new Staff(1, "Alice"),
                    new Staff(2, "Bob"),
                    new Staff(3, "Charlie")
            );
            cacheEligibleStaff(eligibleStaff, hashKey);
        }
    }
}
